package com.zjgeport.zjgdanger.OnPortDynamics;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.soar.PageInfo;
import com.soar.util.net.rmi.httpxml.HttpCallBack;
import com.soar.util.net.rmi.httpxml.HttpClient;
import com.soar.util.net.rmi.httpxml.HttpMethod;
import com.soar.util.net.rmi.httpxml.HttpResult;
import com.zjgeport.zjgdanger.CommonActivity;
import com.zjgeport.zjgdanger.LoginActivity;
import com.zjgeport.zjgdanger.R;
import com.zjgeport.zjgdanger.common.ParamCommon;
import com.zjgeport.zjgdanger.model.myApplication;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class VideoListActivity extends CommonActivity {


    /** Handler What加载数据完毕 **/
    private static final int WHAT_DID_LOAD_DATA = 0;

    /** Handler What更新数据完毕 **/
    private static final int WHAT_DID_REFRESH = 1;

    /** Handler What更多数据完毕 **/
    private static final int WHAT_DID_MORE = 2;

    private ExpandableListView mListView;

    private EditText searchText;

    private Button stretchBtn;

//    private MyCustomAdapter adapter;

    private MyExpandableAdapter expandAdapter;


    /** 分页信息 **/
    protected PageInfo pageInfo = new PageInfo();

    private List<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();

    private List<HashMap<String, String>> dataMore = new ArrayList<HashMap<String, String>>(); // 更多数据列表

    private String sql= "";

    private String keyword = "";

    final List<HashMap<String, String>> companyData = new ArrayList<HashMap<String, String>>();

    final List<HashMap<String, String>> cameraData = new ArrayList<HashMap<String, String>>();

    List<List<HashMap<String, String>>> sameList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_list);
        initCommonListener();
        initView();
    }

    private void initView()
    {
        searchText = findEditTextById(R.id.search_content1);
        searchText.setHint("请输入所属公司");
        searchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if ((actionId == 0 || actionId == 3) && event != null) {

                    keyword = findEditTextStringById(R.id.search_content1);
                    getCompanyList();

                }
                return false;
            }
        });

        float scale = getResources().getDisplayMetrics().density;
        int height = (int) (70 * scale + 0.5f);
		/*
		 * 1.使用PullDownView 2.设置OnPullDownListener 3.从mPullDownView里面获取ListView
		 */

        mListView = (ExpandableListView)findViewById(R.id.pull_down_view);
        expandAdapter = new MyExpandableAdapter(this,companyData,sameList);
        mListView.setDivider(getResources().getDrawable(R.color.white));
        mListView.setSelector(R.color.ap_sel);// 取消点击背景
        mListView.setGroupIndicator(null);
        // 设置可以自动获取更多 滑到最后一个自动获取 改成false将禁用自动获取更多
        getCompanyList();

    }


    /**
     * 初始化数据列表信息
     */
    private void getCompanyList() {

        HttpMethod method = new HttpMethod();
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("keyword", keyword);
        map.put("TOKEN", myApplication.getUser().getToken());
        method.setAction(HttpMethod.SOAR_HTTP_METHOD_ACTION_EXEC);
        method.setClassPath("com.mobile.Execute");
        method.setMethodName("selectCameraCompInfo");
        method.setKvdata(map);
        companyData.clear();
        HttpClient.postdata(new Button(VideoListActivity.this), method, ParamCommon.ptl_server_url, true, new HttpCallBack() {
            @Override
            public void run(HttpResult result) {
                if (result.getResultCode().equals(HttpResult.SOAR_HTTP_STATUS_CODE_SUCCESS)) {
                    List<HashMap<String, String>> data1 = result.getDataSet();
                    if (data1 != null && data1.size() != 0) {
                        companyData.addAll(data1);
                    }

                    getCameraList();


                } else {
                    showToast(result.getResultMessage());
                    if (result.getResultCode().equals("90"))
                    {
                        Intent intent = new Intent(VideoListActivity.this,LoginActivity.class);
                        startActivity(intent);
                    }
                }
//                 刷新UI
                Looper mainLooper = Looper.getMainLooper();
                MyHandler handler = new MyHandler(mainLooper);
                Message msg = new Message();
                msg.what = WHAT_DID_LOAD_DATA;
                msg.obj = companyData;
                handler.sendMessage(msg);

            }
        });
    }

    /**
     * 初始化数据列表信息
     */
    private void getCameraList() {

        HttpMethod method = new HttpMethod();
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("TOKEN", myApplication.getUser().getToken());
        method.setAction(HttpMethod.SOAR_HTTP_METHOD_ACTION_EXEC);
        method.setClassPath("com.mobile.Execute");
        method.setMethodName("selectCameraListInfo");
        method.setKvdata(map);
        cameraData.clear();
        HttpClient.postdata(new Button(VideoListActivity.this), method, ParamCommon.ptl_server_url, true, new HttpCallBack() {
            @Override
            public void run(HttpResult result) {
                if (result.getResultCode().equals(HttpResult.SOAR_HTTP_STATUS_CODE_SUCCESS)) {

                    List<HashMap<String, String>> data1 = result.getDataSet();
                    if (data1 != null && data1.size() != 0) {
                        cameraData.addAll(data1);
                    }



                } else {
                    showToast(result.getResultMessage());
                    if (result.getResultCode().equals("90"))
                    {
                        Intent intent = new Intent(VideoListActivity.this,LoginActivity.class);
                        startActivity(intent);
                    }
                }
                // 刷新UI
                Looper mainLooper = Looper.getMainLooper();
                MyHandler handler = new MyHandler(mainLooper);
                Message msg = new Message();
                msg.what = 999;
                msg.obj = cameraData;
                handler.sendMessage(msg);

            }
        });
    }


    private class MyHandler extends Handler
    {
        public MyHandler(Looper looper)
        {
            super(looper);
        }

        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case WHAT_DID_LOAD_DATA:
                    List<HashMap<String, String>> dataNewList = (List<HashMap<String, String>>) msg.obj;
                    List<HashMap<String, String>> dataCacheList = new ArrayList<HashMap<String, String>>();
                    if (dataNewList != null && dataNewList.size() != 0)
                    {
                        dataList.clear();
                        for (int i = 0; i < dataNewList.size(); i++)
                        {
                            dataList.add(dataNewList.get(i));
                        }
                    }
                    else
                    {
                        if (dataCacheList != null && dataCacheList.size() != 0)
                        {
                            dataList.clear();
                            for (int i = 0; i < dataCacheList.size(); i++)
                            {
                                dataList.add(dataCacheList.get(i));
                            }
                        }
                        else {
                            dataList.clear();
                        }
                    }
//                    adapter.notifyDataSetChanged();
//                    mPullDownView.notifyDidLoad();
                    break;
                case WHAT_DID_REFRESH:
                    expandAdapter.notifyDataSetChanged();
                    break;
                case WHAT_DID_MORE:
                    List<HashMap<String, String>> dataMoreList = (List<HashMap<String, String>>) msg.obj;
                    if (dataMoreList == null)
                    {
                        dataMoreList = new ArrayList<HashMap<String, String>>();
                    }
                    if (dataList != null && dataList.size() != 0)
                    {
                        // 新的List组成，新加载的加上原来的列表
                        dataList.addAll(dataMoreList);
                    }
                    expandAdapter.notifyDataSetChanged();
                    break;
                case 4:

                    break;
                case 999:
                    List<HashMap<String, String>> dataNewList1 = (List<HashMap<String, String>>) msg.obj;
                    sameList.clear();
                    for(int i=0;i<companyData.size();i++)
                    {
                        HashMap<String,String> companyMap = companyData.get(i);
                        List<HashMap<String, String>> cameraArray = new ArrayList<>();
                        for(int j=0;j<cameraData.size();j++)
                        {

                            HashMap<String,String> cameraMap = cameraData.get(j);
                            if (cameraMap.get("COMPANY_NAME").toString().equals(companyMap.get("COMPANY_NAME").toString()))
                            {
                                cameraArray.add(cameraMap);
                            }
                        }
                        sameList.add(i,cameraArray);

                    }
                    if (dataNewList1 != null)
                    {
                        mListView.setAdapter(expandAdapter);
                        expandAdapter.notifyDataSetChanged();;

                    }
                    break;
                default:
                    break;
            }
        }
    }

//    class MyCustomAdapter extends BaseAdapter
//    {
//        private Context main;
//
//        private List<HashMap<String, String>> list;
//
//        public MyCustomAdapter(Context main, List<HashMap<String, String>> list)
//        {
//            this.main = main;
//            this.list = list;
//        }
//
//        public int getCount()
//        {
//            return list.size();
//        }
//
//        public Object getItem(int position)
//        {
//            return list.get(position);
//        }
//
//        public long getItemId(int position)
//        {
//            return position;
//        }
//
//        public View getView(int position, View convertView, ViewGroup parent)
//        {
//            // 如果未选择或list列表为空时直接跳出，避免NullPointException
//            if (position < 0 || list.size() <= 0)
//            {
//                return null;
//            }
//           // 如果为空重新导入ListView的布局文件，布局文件自定义
//            if (convertView == null)
//            {
//                convertView = LayoutInflater.from(main).inflate(R.layout.listitemcamera, null);
//
//            }
//            int endPosition = position+1;
//            if(position <9)
//            {
//                ((TextView) convertView.findViewById(R.id.t1)).setText("0"+endPosition+" "+list.get(position).get("COMPANY_NAME").toString());
//            }
//            else{
//                ((TextView) convertView.findViewById(R.id.t1)).setText(endPosition+" " + list.get(position).get("COMPANY_NAME").toString());
//            }
//
////            ((TextView) convertView.findViewById(R.id.t2)).setText(list.get(position).get("HS_NAME").toString());
////            ((TextView) convertView.findViewById(R.id.t3)).setText(list.get(position).get("HS_UNIT").toString());
////            ((TextView) convertView.findViewById(R.id.t4)).setText(list.get(position).get("UPDATE_DATE").toString());
//            TextView t2 = (TextView)convertView.findViewById(R.id.t2);
//            TextView t3 = (TextView)convertView.findViewById(R.id.t3);
//            TextView t4 = (TextView)convertView.findViewById(R.id.t4);
//            TextView t5 = (TextView)convertView.findViewById(R.id.t5);
//            TextView t6 = (TextView)convertView.findViewById(R.id.t6);
//
//            String companyName = list.get(position).get("COMPANY_NAME").toString();
//
//            List<HashMap<String, String>> cameraList = new ArrayList<>();
//
//            cameraList = sameList.get(companyName);
//
//            if (cameraList != null && cameraList.size()>0)
//            {
//                HashMap<String,String> FirstMap = cameraList.get(0);
//                t2.setText(FirstMap.get("CAMERA_NAME").toString());
//                t3.setText(FirstMap.get("CAMERA_CODE").toString());
//                t4.setText(FirstMap.get("INDEX_CODE").toString());
//                t5.setText(FirstMap.get("LAT").toString());
//                t6.setText(FirstMap.get("LNG").toString());
//
//                stretchBtn = convertView.findViewById(R.id.stretch);
//                final  LinearLayout layll = (LinearLayout) convertView.findViewById(R.id.laycontent);
//                stretchBtn.setOnClickListener(new View.OnClickListener()
//                {
//                    public void onClick(View v)
//                    {
//                        boolean isDown = false;
//                        ViewGroup.LayoutParams lp = layll.getLayoutParams();
//                        float scale = getResources().getDisplayMetrics().density;
//                        int height = (int) (lp.height / scale + 0.5f);
//                        if(height > 218)
//                        {
//                            lp.height = (int)(218 * scale+0.5f) ;
//                            isDown = false;
//                        }
//                        else{
//                            lp.height= (int)(218*scale*sameList.size()+0.5f);
//                            isDown = true;
//                        }
//                        if (isDown)
//                        {
//                            stretchBtn.setBackgroundResource(R.drawable.down_arrow);
//                        }
//                        else{
//                            stretchBtn.setBackgroundResource(R.drawable.up_arrow);
//                        }
//                        layll.setLayoutParams(lp);
//
//                    }
//                });
//
//                if (cameraList.size()>1)
//                {
//                    LinearLayout lay = (LinearLayout) convertView.findViewById(R.id.laycontent); // 获取XML公共布局
//                    for (int i = 1; i < cameraList.size(); i++)
//                    {
//                        HashMap<String, String> map = cameraList.get(i);
//                        LinearLayout laychild = (LinearLayout) getLayoutInflater().inflate(R.layout.cameralistchild, null);
//                        // 数据赋值
//                        TextView childt2, childt3,childt4,childt5,childt6;
//                        childt2 = (TextView) laychild.findViewById(R.id.t2);
//                        childt3 = (TextView) laychild.findViewById(R.id.t3);
//                        childt4 = (TextView) laychild.findViewById(R.id.t4);
//                        childt5 = (TextView) laychild.findViewById(R.id.t5);
//                        childt6 = (TextView) laychild.findViewById(R.id.t6);
//                        childt2.setText(map.get("CAMERA_NAME").toString());
//                        childt3.setText(map.get("CAMERA_CODE").toString());
//                        childt4.setText(map.get("INDEX_CODE").toString());
//                        childt5.setText(map.get("LAT").toString());
//                        childt6.setText(map.get("LNG").toString());
//                        lay.addView(laychild);
//                    }
//                }
//            }
//            return convertView;
//        }
//    }

    class MyExpandableAdapter extends BaseExpandableListAdapter {

        List<HashMap<String, String>> groupArray;
        private List<List<HashMap<String, String>>> childArray;
        private Context mContext;

        public MyExpandableAdapter(Context context,List<HashMap<String, String>> groupArray, List<List<HashMap<String, String>>> childArray){
            mContext = context;
            this.groupArray = groupArray;
            this.childArray = childArray;
        }

        @Override
        public int getGroupCount() {
            return groupArray.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return childArray.get(groupPosition).size()-1;
        }

        @Override
        public Object getGroup(int groupPosition) {
            return groupArray.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return childArray.get(groupPosition).get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public View getGroupView(final int groupPosition, final boolean isExpanded, View convertView, ViewGroup parent) {
            View view = convertView;
            GroupHolder holder = null;
            if(view == null){
                holder = new GroupHolder();
                view = LayoutInflater.from(mContext).inflate(R.layout.listitemcamera, null);
                holder.t1 = (TextView)view.findViewById(R.id.t1);
                holder.t2 = (TextView)view.findViewById(R.id.t2);
                holder.t3 = (TextView)view.findViewById(R.id.t3);
                holder.t4 = (TextView)view.findViewById(R.id.t4);
                holder.t5 = (TextView)view.findViewById(R.id.t5);
                holder.t6 = (TextView)view.findViewById(R.id.t6);
                holder.arrow = (Button)view.findViewById(R.id.stretch);
                view.setTag(holder);
            }else{
                holder = (GroupHolder)view.getTag();
            }

            //判断是否已经打开列表
            if(isExpanded){
                holder.arrow.setBackgroundResource(R.drawable.uparrow);
            }else{
                holder.arrow.setBackgroundResource(R.drawable.downarrow);
            }

            holder.arrow.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View v)
                {
                   if (isExpanded)
                   {
                       mListView.collapseGroup(groupPosition);
                   }
                   else{
                       mListView.expandGroup(groupPosition);
                   }
                }
            });

            int endPosition = groupPosition+1;
            holder.t1.setText("0"+endPosition+" "+groupArray.get(groupPosition).get("COMPANY_NAME").toString());
            if (childArray.size()>0 && childArray != null)
            {
                HashMap<String, String> map = childArray.get(groupPosition).get(0);
                holder.t2.setText(map.get("CAMERA_NAME").toString());
                holder.t3.setText(map.get("CAMERA_CODE").toString());
                holder.t4.setText(map.get("INDEX_CODE").toString());
                holder.t5.setText(map.get("LAT").toString());
                holder.t6.setText(map.get("LNG").toString());
            }

            return view;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            View view = convertView;
            ChildHolder holder = null;
            if(view == null){
                holder = new ChildHolder();
                view = LayoutInflater.from(mContext).inflate(R.layout.cameralistchild, null);
                holder.childtv2 = (TextView)view.findViewById(R.id.t2);
                holder.childtv3 = (TextView) view.findViewById(R.id.t3);
                holder.childtv4 = (TextView) view.findViewById(R.id.t4);
                holder.childtv5 = (TextView) view.findViewById(R.id.t5);
                holder.childtv6 = (TextView) view.findViewById(R.id.t6);
                view.setTag(holder);
            }else{
                holder = (ChildHolder)view.getTag();
            }

            if(childPosition == childArray.get(groupPosition).size()-1)
            {

            }
            else {
                HashMap<String, String> map = childArray.get(groupPosition).get(childPosition+1);
                holder.childtv2.setText(map.get("CAMERA_NAME").toString());
                holder.childtv3.setText(map.get("CAMERA_CODE").toString());
                holder.childtv4.setText(map.get("INDEX_CODE").toString());
                holder.childtv5.setText(map.get("LAT").toString());
                holder.childtv6.setText(map.get("LNG").toString());
            }


            return view;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        class GroupHolder{
            public TextView t1;
            public TextView t2;
            public TextView t3;
            public TextView t4;
            public TextView t5;
            public TextView t6;
            public Button arrow;

        }

        class ChildHolder{
            public TextView childtv2;
            public TextView childtv3;
            public TextView childtv4;
            public TextView childtv5;
            public TextView childtv6;
        }
    }
}


